﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using VAdvantage.Classes;
using VAdvantage.Utility;
using VAdvantage.Model;
using System.Text;
using VAdvantage.Logging;
using System.Data;
using VAdvantage.DataBase;
using System.Threading;
using System.Reflection;
using VAdvantage.Apps.AForms;

namespace VAdvantage.Apps
{
    public class FormFrame : CFrame
    {
        #region Private variables
        // Save Button			
        public AppsAction aSave;
        // Private Lock Button	
        public AppsAction aLock;
        //	Local (added to toolbar)
        private AppsAction aReport, aEnd, aHelp, aExit;
        private AppsAction aPrevious, aNext, aParent, aDetail, aFirst, aLast,
                           aNew, aCopy, aDelete, aIgnore, aPrint,
                           aRefresh, aAttachment, aChat, aMulti, aFind,
                           aWorkflow, aZoomAcross, aRequest, aUserDef, aArchive;
        //	Last Modifier of Action Event					
        private int _lastModifiers;
        //WindowNo	
        private int _windowNo;
        //	Description					
        private String _description = null;
        private String _displayName = "";
        //Help					
        private String _help = null;
        //Menu Bar					
        // private  MenuStrip menuBar = new MenuStrip();
        //The Panel to be displayed
        private FormPanel _panel = null;
        // Maximize Window				
        public bool _maximize = false;
        //	Static Logger	
        private static VLogger log = VLogger.GetVLogger(typeof(FormFrame).FullName);
        #endregion

        /// <summary>
        /// Constructor
        /// </summary>
        public FormFrame()
            : base("")
        {
            VAdvantage.Utility.Envs.RegisterWindowForm(this);
            //this.BackColor = DataBase.GlobalVariable.WINDOW_BACK_COLOR;//silverlight coment

            _windowNo = Envs.CreateWindowNo(this);
            try
            {
                JbInit();
                CreateMenu();

            }
            catch (Exception e)
            {
                log.Log(Level.SEVERE, "", e);
            }
        }

        /// <summary>
        /// Static Init
        /// </summary>
        private void JbInit()
        {
        }


        /// <summary>
        /// Create Menu
        /// </summary>
        private void CreateMenu()
        {

            ////      File
            //ToolStripMenuItem mFile = AEnv.GetMenu("File");
            //menuBar.Items.Add(mFile);
            //AEnv.AddMenuItem("PrintScreen", null, Keys.None, mFile, this).Click += new EventHandler(this.ActionPerformed);
            //AEnv.AddMenuItem("ScreenShot", null, Keys.None, mFile, this).Click += new EventHandler(this.ActionPerformed);
            ////KeyStroke.getKeyStroke(KeyEvent.VK_PRINTSCREEN, Event.SHIFT_MASK)
            //AEnv.AddMenuItem("Report", null, Keys.None, mFile, this).Click += new EventHandler(this.ActionPerformed);//KeyStroke.getKeyStroke(KeyEvent.VK_P, Event.ALT_MASK)
            ////mFile.addSeparator();
            //mFile.DropDown.Items.Add(new ToolStripSeparator());
            //AEnv.AddMenuItem("End", null, Keys.None, mFile, this).Click += new EventHandler(this.ActionPerformed);//KeyStroke.getKeyStroke(KeyEvent.VK_X, Event.ALT_MASK)
            //AEnv.AddMenuItem("Exit", null, Keys.None, mFile, this).Click += new EventHandler(this.ActionPerformed);//KeyStroke.getKeyStroke(KeyEvent.VK_X, Event.SHIFT_MASK + Event.ALT_MASK)

            ////      View
            //ToolStripMenuItem mView = AEnv.GetMenu("View");
            //menuBar.Items.Add(mView);
            //AEnv.AddMenuItem("InfoProduct", null, Keys.None, mView, this).Click += new EventHandler(this.ActionPerformed);//KeyStroke.getKeyStroke(KeyEvent.VK_I, Event.CTRL_MASK)
            //AEnv.AddMenuItem("InfoBPartner", null, Keys.None, mView, this).Click += new EventHandler(this.ActionPerformed);//KeyStroke.getKeyStroke(KeyEvent.VK_I, Event.SHIFT_MASK + Event.CTRL_MASK)
            //AEnv.AddMenuItem("InfoAccount", null, Keys.None, mView, this).Click += new EventHandler(this.ActionPerformed);//KeyStroke.getKeyStroke(KeyEvent.VK_I, Event.ALT_MASK + Event.CTRL_MASK)
            ////mView.addSeparator();
            //mView.DropDown.Items.Add(new ToolStripSeparator());
            //AEnv.AddMenuItem("InfoOrder", "Info", Keys.None, mView, this).Click += new EventHandler(this.ActionPerformed);
            //AEnv.AddMenuItem("InfoInvoice", "Info", Keys.None, mView, this).Click += new EventHandler(this.ActionPerformed);
            //AEnv.AddMenuItem("InfoInOut", "Info", Keys.None, mView, this).Click += new EventHandler(this.ActionPerformed);
            //AEnv.AddMenuItem("InfoPayment", "Info", Keys.None, mView, this).Click += new EventHandler(this.ActionPerformed);
            //AEnv.AddMenuItem("InfoSchedule", "Info", Keys.None, mView, this).Click += new EventHandler(this.ActionPerformed);

            ////      Tools
            //ToolStripMenuItem mTools = AEnv.GetMenu("Tools");
            //menuBar.Items.Add(mTools);
            //AEnv.AddMenuItem("Calculator", null, Keys.None, mTools, this).Click += new EventHandler(this.ActionPerformed);
            //AEnv.AddMenuItem("Calendar", null, Keys.None, mTools, this).Click += new EventHandler(this.ActionPerformed);
            //AEnv.AddMenuItem("Editor", null, Keys.None, mTools, this).Click += new EventHandler(this.ActionPerformed);
            //AEnv.AddMenuItem("Script", null, Keys.None, mTools, this).Click += new EventHandler(this.ActionPerformed);
            //if (MRole.GetDefault().IsShowPreference())
            //{
            //    //mTools.addSeparator();
            //    mTools.DropDown.Items.Add(new ToolStripSeparator());
            //    AEnv.AddMenuItem("Preference", null, Keys.None, mTools, this).Click += new EventHandler(this.ActionPerformed);
            //}

            ////      Help
            //ToolStripMenuItem mHelp = AEnv.GetMenu("Help");
            //menuBar.Items.Add(mHelp);
            //AEnv.AddMenuItem("Help", "Help", Keys.None, mHelp, this).Click += new EventHandler(this.ActionPerformed);//KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0)
            //AEnv.AddMenuItem("Online", null, Keys.None, mHelp, this).Click += new EventHandler(this.ActionPerformed);
            //AEnv.AddMenuItem("EMailSupport", null, Keys.None, mHelp, this).Click += new EventHandler(this.ActionPerformed);
            //AEnv.AddMenuItem("About", null, Keys.None, mHelp, this).Click += new EventHandler(this.ActionPerformed);
            //// this.MainMenuStrip = this.menuBar;
            //this.SetMenuBar(menuBar);
            ////this.GetMenuPane().Controls.Add(this.menuBar);
            ////menuBar.BackColor = Color.Red;
        }

        // Dispose active 
        private bool _disposing = false;

        /// <summary>
        /// handler menu and tool bar event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void ActionPerformed(object sender, RoutedEventArgs e)
        {
            string cmd = "";
            if (sender is IActionName)
            {
                cmd = ((IActionName)sender).ActionName;
            }
            //else if (sender is ToolStripMenuItem)
            //{
            //    cmd = ((ToolStripMenuItem)sender).Name;
            //}
            // log.Info(cmd + " - " + Control.ModifierKeys);
            // _lastModifiers = (int)(Control.ModifierKeys);

            if (cmd.Equals("End"))
            {
                this.Close();
            }
            else if (cmd.Equals("Help"))
            {
                ActionHelp();
            }
            //else if (!AEnv.ActionPerformed(cmd, _windowNo, this))
            //{
            //    log.Log(Level.SEVERE, "Not handeled=" + cmd);
            //}
        }

        /// <summary>
        /// Dispose
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            
            log.Config("");
            //	recursive calls
            try
            {
                 //_panel.Dispose();
            }
            catch { }
            _panel = null;
            Envs.ClearWinContext(_windowNo);
            base.Dispose(disposing);
        }



        /// <summary>
        /// Open Form
        /// </summary>
        /// <param name="AD_Form_ID">form</param>
        /// <returns>true if form opened</returns>
        public bool OpenForm(int AD_Form_ID)
        {

            Context ctx = Envs.GetContext();
            String name = null;
           
            String className = null;
            bool isReport  = false;
            String sql = "SELECT Name, Description, Classname, Help , IsReport, DisplayName FROM AD_Form WHERE AD_Form_ID=" + AD_Form_ID;  //jz ClassName, AD?
            bool trl = !Envs.IsBaseLanguage(ctx, "AD_Form");
            if (trl)
            {
                sql = " SELECT t.Name, t.Description, f.Classname, t.Help ,f.IsReport" //jz
                    + " FROM AD_Form f INNER JOIN AD_Form_Trl t"
                    + " ON (f.AD_Form_ID=t.AD_Form_ID AND AD_Language='" + Envs.GetAD_Language(ctx) + "')"
                    + " WHERE f.AD_Form_ID=" + AD_Form_ID;
            }

            IDataReader idr = null;
            DataTable dt = null;
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {

                try
                {
                    idr = DB.ExecuteReader(sql, null, null);
                    dt = new DataTable();
                    dt.Load(idr);
                    idr.Close();
                    foreach (DataRow dr in dt.Rows)
                    {
                        name = Util.GetValueOfString(dr[0]);
                        _description = Util.GetValueOfString(dr[1]);
                        if (dr["IsReport"].ToString().Equals("Y", StringComparison.OrdinalIgnoreCase))
                        {
                            className = "VAdvantage.Report.ReportLoader";
                            isReport = true;
                        }
                        else
                            className = dr[2].ToString();
                        //className = Util.GetValueOfString(dr[2]);
                        _help = Util.GetValueOfString(dr[3]);
                        if (!trl)
                        {
                            _displayName = Util.GetValueOfString(dr[5]);
                        }
                    }

                }
                catch (Exception e)
                {
                    if (idr != null)
                    {
                        idr.Close();
                    }
                    log.Log(Level.SEVERE, sql, e);
                }
                if (className == null)
                {
                    //return false;
                }
                else
                { 
                    className = className.Replace("org.compiere.apps.form", "VAdvantage.Apps.AForms");
                    className = className.Replace("org.compiere.install", "VAdvantage.Install");
                    // bool success = OpenForm(AD_Form_ID, className, name);
                    //	Log
                    MSession session = MSession.Get(ctx, true);
                    session.WindowLog(ctx.GetAD_Client_ID(), ctx.GetAD_Org_ID(), 0, AD_Form_ID);
                    Deployment.Current.Dispatcher.BeginInvoke(() => OpenForm(AD_Form_ID, className, name, isReport));
                }
            });

            return true;
        }


        int AD_Table_ID = 0;

        public void SetTable_ID(int tableID)
        {
            AD_Table_ID = tableID;
        }

        public void OpenForm(int AD_Form_ID, String className, String name)
        {
            OpenForm(AD_Form_ID, className, name, false);
        }

       
        /// <summary>
        /// Open Form
        /// </summary>
        /// <param name="AD_Form_ID">Form</param>
        /// <param name="className">class name</param>
        /// <param name="name">title</param>
        /// <returns>true if started</returns>
        public void OpenForm(int AD_Form_ID, String className,string name,bool isReport)
        {
            log.Info("AD_Form_ID=" + AD_Form_ID + " - Class=" + className);
            Context ctx = Envs.GetContext();
            if(string.IsNullOrEmpty(_displayName))
            {
                _displayName = name;
            }
            ctx.SetContext(_windowNo, "WindowName", _displayName);
            SetTitle(Envs.GetHeader(ctx, _windowNo));
            try
            {
                Assembly asm = null;
                Type type = null;

                /************  Module ****************/
                try
                {
                    //string formName = className.Substring(className.LastIndexOf('.') + 1);
                    Tuple<String, String> asmInfo = null;
                    if (Envs.HasModulePrefix(name, out asmInfo))
                    {
                        asm = Assembly.Load(asmInfo.Item1);
                        type = asm.GetType(className);
                    }
                }
                catch ( Exception e)
                {
                    log.Warning("Assembly => " + e.Message);
                }
                /********************* END ******************/

                if (type == null)
                {
                    try
                    {
                        asm = Assembly.Load(GlobalVariable.PRODUCT_NAME);
                        type = asm.GetType(className);
                    }
                    catch
                    {
                        //asm = Assembly.Load(GlobalVariable.ASSEMBLY_NAME);
                    }
                }
                
                /*End Customization */

                if (type == null)
                {
                    type = Type.GetType(className);
                }
                this.Set_Ad_Form_ID(AD_Form_ID);
               
                //	Create instance w/o parameters
                //_panel = (FormPanel)Class.forName(className).newInstance();
                _panel = (FormPanel)Activator.CreateInstance(type);

            }
            catch (Exception e)
            {
                log.Log(Level.SEVERE, "Class=" + className + ", AD_Form_ID=" + AD_Form_ID, e);
                // return false;
            }
            //
            if (_panel != null)
            {
                _panel.Init(_windowNo, this);

                if (_panel == null)
                {
                    Envs.SetBusyIndicator(false);
                    return;
                }

                if (AD_Form_ID.Equals(118) && AD_Table_ID > 0) //explicitly for Archive Viewer (Jagmohan Bhatt)
                {
                    ArchiveViewer archive = (ArchiveViewer)_panel;
                    archive.SetTableID(true, AD_Table_ID, 0);
                }
            }
            else
            {
                log.Severe("could not find type against form class [step 2]");
                ShowMessage.Error("Error?", true, "class not found");
                Envs.SetBusyIndicator(false);
                return;
                //MessageBox.Show(" _panel 2b is Null ");
            }

            if (!isReport) //Not Crystal report form
            {
               // this.Show();
                Envs.ShowForm(this);
                Envs.SetBusyIndicator(false);
            }
            

        }

        /// <summary>
        /// Get Form Panel
        /// </summary>
        /// <returns>form panel</returns>
        public FormPanel GetFormPanel()
        {
            return _panel;
        }

        /**
         * 	Action Listener
         * 	@param e event
         */
        //public void actionPerformed(ActionEvent e)
        //{
        //    String cmd = e.getActionCommand();
        //    if (cmd.equals("End"))
        //        dispose();
        //    else if (cmd.equals("Help"))
        //        actionHelp();
        //    else if (!AEnv.actionPerformed(cmd, m_WindowNo, this))
        //        log.log(Level.SEVERE, "Not handeled=" + cmd);
        //}  

        /// <summary>
        /// Show Help
        /// </summary>
        private void ActionHelp()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<h2>").Append(_description).Append("</h2><p>")
                .Append(_help);
            //Help hlp = new Help (Env.GetForm(this), this.getTitle(), sb.ToString());

            //hlp.setVisible(true);
        }

        /// <summary>
        /// Set Window Busy
        /// </summary>
        /// <param name="busy">busy</param>
        public void SetBusy(bool busy)
        {
            //if (busy == _glassPane.isVisible())
            //{
            //    return;
            //}
            log.Info("Busy=" + busy);
            if (busy)
            {
                // setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
            }
            else
            {
                //setCursor(Cursor.getDefaultCursor());
            }
            //_glassPane.setMessage(null);
            //_glassPane.setVisible(busy);
            //_glassPane.requestFocus();
        }

        /// <summary>
        /// Set Busy Message
        /// </summary>
        /// <param name="AD_Message">message</param>
        public void SetBusyMessage(String AD_Message)
        {
            //_glassPane.setMessage(AD_Message);
        }

        /// <summary>
        /// Set and start Busy Counter
        /// </summary>
        /// <param name="time">time in seconds</param>
        public void SetBusyTimer(int time)
        {
            //_glassPane.setBusyTimer (time);
        }

        /// <summary>
        /// Set Maximize Window
        /// </summary>
        /// <param name="max">maximize</param>
        public void SetMaximize(bool max)
        {
            _maximize = max;
        }

        int m_Ad_CrystalInstance_ID = 0;
        int m_AD_Form_ID = 0;
       
        public int Get_Ad_CrystalInstance_ID()
        {
            return m_Ad_CrystalInstance_ID;
        }

        public void Set_Ad_CrystalInstance_ID(int Ad_CrystalInstance_ID)
        {
            m_Ad_CrystalInstance_ID = Ad_CrystalInstance_ID;
        }

        public int Get_Ad_Form_ID()
        {
            return m_AD_Form_ID;
        }

        public void Set_Ad_Form_ID(int AD_Form_ID)
        {
            m_AD_Form_ID = AD_Form_ID;
        }

        bool isCalledFromAPanel;

        public bool IsCalledFromAPanel()
        {
            return isCalledFromAPanel;
        }

        public void Set_IsCalledFromAPanel(bool _isCalledFromAPanel)
        {
            isCalledFromAPanel = _isCalledFromAPanel;
        }



        //work for Crystal reports
#region 
        string m_proceedure = "";

        public void SetProcedureName(string pName)
        {
            m_proceedure = pName;
        }

        public string GetProcedureName()
        {
            return m_proceedure;
        }

        public List<String> ColNames
        {
            get;
            set;
        }
        public List<object> ColValues
        {
            get;
            set;
        }
#endregion

    }
}
